package edu.zju.gis.dbfg.server.exception;

import edu.zju.gis.dbfg.common.Result;
import edu.zju.gis.dbfg.common.base.BaseException;
import edu.zju.gis.dbfg.common.constant.CodeConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author Hu
 * @date 2019/4/29
 * 用于处理全局异常，进行统一格式化后返回前端
 **/
@ControllerAdvice
public class GlobalExceptionHandler {

  /**
   * 全局异常捕捉处理
   * @param ex
   * @return
   */
  @ResponseBody
  @ExceptionHandler(value = BaseException.class)
  public Result errorHandler(BaseException ex) {
    return Result.error().setCode(ex.getCode()).setMessage(ex.getMessage());
  }

  @ResponseBody
  @ExceptionHandler
  public Result duplicateErrorHandler(SQLIntegrityConstraintViolationException ex) {
    return Result.error().setCode(CodeConstants.DAO_ERROR).setMessage(ex.getMessage());
  }

}
